<?php
namespace Admin\Controller;
use Admin\Logic\OrderLogic;
use Admin\Logic\GoodsLogic;
use WXAPI\Controller\PintLogic;
use Think\AjaxPage;
use Think\Page;

class PintController extends BaseController {

    /**
     *  商品列表
     */
    public function goodsList(){      
        $GoodsLogic = new GoodsLogic();        
        $brandList = $GoodsLogic->getSortBrandsPt();
        $categoryList = $GoodsLogic->getSortCategoryPt();
        $wxapi = new \WXAPI\Controller\PintController;
        $wxapi->pint_check_order();
        $this->assign('categoryList',$categoryList);
        $this->assign('brandList',$brandList);
        $this->display();                                           
    }
    
    /**
     *  商品列表
     */
    public function ajaxGoodsList(){            
        
        $where = ' 1 = 1 '; // 搜索条件                
        I('intro')    && $where = "$where and ".I('intro')." = 1" ;        
        I('brand_id') && $where = "$where and brand_id = ".I('brand_id') ;
        (I('goods_state') !== '') && $where = "$where and goods_state = ".I('goods_state') ;                
        $cat_id = I('cat_id');
        // 关键词搜索               
        $key_word = I('key_word') ? trim(I('key_word')) : '';
        if($key_word)
        {
            $where = "$where and (goods_name like '%$key_word%' or goods_sn like '%$key_word%')" ;
        }
        
        if($cat_id > 0)
        {            
            $where .= " and (cat_id1 = $cat_id or cat_id2 = $cat_id or cat_id3 = $cat_id ) "; // 初始化搜索条件
        }        
        $where .= " and is_pint = 1 ";
        $model = M('Goods');
        $count = $model->where($where)->count();
        $Page  = new AjaxPage($count,10);
		
        $show = $Page->show();
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        $goodsList = $model->where($where)->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();

		foreach ($goodsList as $k => $v) {
			
			$goodsList[$k]['store_name']= M('store')->where(array('store_id'=>$v['store_id']))->getField("store_name");
        }

        $catList = D('goods_category')->select();
        $catList = convert_arr_key($catList, 'id');
        $goods_state = C('goods_state');
        $this->assign('catList',$catList);
        $this->assign('goodsList',$goodsList);
        $this->assign('goods_state',$goods_state);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();         
    }

    /**
     * 商品批量操作
     */
    public function act()
    {
        $act = I('post.act', '');
        $goods_ids = I('post.goods_ids');
        $goods_state = I('post.goods_state');
        $reason = I('post.reason');

        $return_success = array('status' => 1, 'msg' => '操作成功', 'data' => '');
        if ($act == 'pt_hot') {
            $pt_hot['goods_id'] = array('in', $goods_ids);
            M('goods')->where($pt_hot)->save(array('pt_hot' => 1));
            $this->ajaxReturn($return_success);
        }
        if ($act == 'pt_hot_not') {
            $pt_hot_not['goods_id'] = array('in', $goods_ids);
            M('goods')->where($pt_hot_not)->save(array('pt_hot' => 0));
            $this->ajaxReturn($return_success);
        }
        if ($act = 'examine') {
            $goods_array = explode(',', $goods_ids);
            $goods_state_cg = C('goods_state');
            if (!array_key_exists($goods_state, $goods_state_cg)) {
                $return_success = array('status' => -1, 'msg' => '操作失败，商品没有这种属性', 'data' => '');
                $this->ajaxReturn($return_success);
            }
            foreach ($goods_array as $key => $val) {
                $update_goods_state = M('goods')->where("goods_id = $val")->save(array('goods_state' => $goods_state));
                if ($update_goods_state) {
                    $update_goods = M('goods')->where(array('goods_id' => $val))->find();
                    // 给商家发站内消息 告诉商家商品被批量操作
                    $store_msg = array(
                        'store_id' => $update_goods['store_id'],
                        'content' => "您的商品\"{$update_goods[goods_name]}\"被{$goods_state_cg[$goods_state]},原因:{$reason}",
                        'addtime' => time(),
                    );
                    M('store_msg')->add($store_msg);
                }
            }
            $this->ajaxReturn($return_success);
        }
        $return_fail = array('status' => -1, 'msg' => '没有找到该批量操作', 'data' => '');
        $this->ajaxReturn($return_fail);
    }

     //拼团列表
    public function pintList(){
    	$wxapi = new \WXAPI\Controller\PintController;
        $wxapi->pint_check_order();
        $this->display();
    }
    
    /**
     *  拼团列表
     */
    public function ajaxPintList(){         
        
        $where = " 1=1 ";
        $pint_status = I('pint_status');
        if($pint_status != 3){
            $where = "$where and pint_status ='$pint_status'" ;
        }

        // 会员id搜索       
        $user_id = I('user_id') ? trim(I('user_id')) : '0';

        if($user_id)
        {
            $where = "$where and user_id ='$user_id'" ;
        }

        // 商品id搜索               
        $goods_id = I('goods_id') ? trim(I('goods_id')) : '0';
        if($goods_id)
        {
            $where = "$where and goods_id ='$goods_id'" ;
        }
        

        $model = M('Pint');
        $count = $model->where($where)->count();

        // var_dump($where);
        // var_dump($count);
        $Page  = new AjaxPage($count,10);
        
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        
        // 是否从缓存中获取Page
        if(session('is_back')==1){
            $Page = getPageFromCache();
            //重置获取条件
            delIsBack();
        }
        
        $pintList = $model->where($where)->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();
        if($pintList){
            $g = array();
            $u = array();
            foreach($pintList as $v){
                $g[] = $v['goods_id'];
                $u[] = $v['user_id'];
            }
            $u = implode(',',array_unique($u));
            $g = implode(',',array_unique($g));
            $goods = M()->query("select goods_id,goods_name from ty_goods where goods_id in (".$g.")");
            $users = M()->query("select user_id,nickname from ty_users where user_id in (".$u.")");

            $g = array();
            $u = array();
            foreach($goods as $v){
                $g[$v['goods_id']] = $v['goods_name'];
            }
            foreach($users as $v){
                $u[$v['user_id']] = $v['nickname'];
            }
            $this->assign('g',$g);
            $this->assign('u',$u);
        }
        cachePage($Page);
        $show = $Page->show();
            
        $this->assign('stus',array(0=>'拼团中',1=>'拼团成功',2=>'拼团失败'));
        
        $this->assign('pintList',$pintList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }


    /**
     * 查看拼团详情
     */
    public function pintInfo(){

        $pint_id = I('pint_id');
        $pint = M('pint')->find($pint_id);
        if(!$pint){
            echo '找不到该拼团信息';
            die;
        }
        $u = M('users');
        $o = M('order');
        $goods = M('goods')->find($pint['goods_id']);
        $users['tuanzhang_id'] = $pint['user_id'];
        $users = M('order')->where(array('order_prom_type'=>'101','order_prom_id'=>$pint_id))->where("!(pay_code!='cod' and pay_status=0)")->select();
        $goods = M('goods')->find($pint['goods_id']);
        $this->assign('pint',$pint);
        $this->assign('goods',$goods);
        $this->assign('users',$users);
        $this->assign('pint_stus',array(0=>'进行中',1=>'拼团成功',2=>'拼团失败'));
        $order_status = C('ORDER_STATUS');
        $pay_status = C('PAY_STATUS');
        $shipping_status = C('SHIPPING_STATUS');
        $this->assign('order_status',$order_status);
        $this->assign('pay_status',$pay_status);
        $this->assign('shipping_status',$shipping_status);
        $this->display();
    }


    public function PintRule(){
        $rule1 = M("config")->where(array("inc_type"=>"pintRule"))->select();
        $rule = array();
        foreach($rule1 as $v){
            $rule[$v['name']] = $v['value'];
        }
        $in_rule = explode(',',$rule['pint_types']);


        $types = M('goods_category')->field("id,name")->where(array("parent_id"=>0))->select();
        $t = array();
        if(in_array("-1",$in_rule)){
            $t['-1'] = array("name"=>"热销","is"=>1);
        }else{
            $t['-1'] = array("name"=>"热销","is"=>0);
        }
        foreach($types as $v){
            if(in_array($v['id'],$in_rule)){
                $t[$v['id']] = array("name"=>$v['name'],"is"=>1);
            }else{
                $t[$v['id']] = array("name"=>$v['name'],"is"=>0);
            }
        }
        $PintImages = explode(',',$rule['pint_images']);
        $this->assign("type",$t);
        $this->assign("PintImages",$PintImages);
        $this->assign("rule",$rule);
        $this->initEditor(); // 编辑器
        $this->display();
    }
    /**
     * 初始化编辑器链接     
     * 本编辑器参考 地址 http://fex.baidu.com/ueditor/
     */
    private function initEditor()
    {
        $this->assign("URL_upload", U('Admin/Ueditor/imageUp',array('savepath'=>'goods'))); // 图片上传目录
        $this->assign("URL_imageUp", U('Admin/Ueditor/imageUp',array('savepath'=>'article'))); //  不知道啥图片
        $this->assign("URL_fileUp", U('Admin/Ueditor/fileUp',array('savepath'=>'article'))); // 文件上传s
        $this->assign("URL_scrawlUp", U('Admin/Ueditor/scrawlUp',array('savepath'=>'article')));  //  图片流
        $this->assign("URL_getRemoteImage", U('Admin/Ueditor/getRemoteImage',array('savepath'=>'article'))); // 远程图片管理
        $this->assign("URL_imageManager", U('Admin/Ueditor/imageManager',array('savepath'=>'article'))); // 图片管理        
        $this->assign("URL_getMovie", U('Admin/Ueditor/getMovie',array('savepath'=>'article'))); // 视频上传
        $this->assign("URL_Home", "");
    }    

    //拼团开启后循环处理超时未完成的拼团
    public function del_order_while(){
        ignore_user_abort(true);
        set_time_limit(0);
        date_default_timezone_set("PRC");
        ini_set('memory_limit','512M');
        $t = M('test');
        do{
            $t->add(array('an'=>date('Y-m-d H:i:s',time())));
        //     $can = M('config')->where(array('name'=>'pint_can'))->getField('value');
        //     if(!$can){
        //         sleep(10);
        //         continue;
        //     }
        //     $this->pint_check_order();
            sleep(30);
            
        }while(true);
    }


    //换一种思路，每次有人访问小程序时候，就去判断一次，也可以
    //拼团失败删除订单
    // public function pint_check_order(){
    //     $can = M('config')->where(array('name'=>'pint_can'))->getField('value');
    //     if($can){
    //         $time = time();
    //         $pints = M('pint')->where('pint_stop_time <='.$time.' and pint_status=0')->select();
    //         if($pints){
    //             $or = M('order');
    //             M('pint')->where('pint_stop_time <='.$time.' and pint_status=0')->save(array('pint_status'=>2));
    //             $ids = array();
    //             foreach($pints as $p){
    //                 $ids[] = $p['pint_id'];
    //             }
    //             $id = implode(',',$ids);
    //             $orders = $or->where('order_prom_type = 101 and order_prom_id in('.$id.')')->select();

    //             $ids = '';
    //             $data = array();
    //             $time = time();
    //             foreach ($orders as $k => $v) {
    //                 //退款退积分退红包退余额
    //                 //付款全部退还至月，积分全部退还值积分
    //                 $money = 0;
    //                 if($v['pay_status'] == 1 && $v['pay_code'] != 'cod'){
    //                     $money += $v['user_money'];
    //                     $money += $v['order_amount'];
    //                 }else if($v['pay_code'] == 'cod' && $v['user_money'] > 0){
    //                     $money += $v['user_money'];
    //                 }
    //                 if($money > 0){
    //                     $or->where(array('order_id'=>$v['order_id']))->setInc('user_money',$money);
    //                 }
    //                 if($v['integral'] > 0){
    //                     $or->where(array('order_id'=>$v['order_id']))->setInc('pay_points',$v['integral']);
    //                 }
    //                 $ids .= $v['order_id'].',';
    //                 $data[] = array(
    //                     'order_id' => $v['order_id'],
    //                     'action_user' => $v['user_id'],
    //                     'action_note' => '系统自动取消订单',
    //                     'order_status' => 3,
    //                     'log_time' => $time,
    //                     'status_desc' => '拼团超时,取消订单',
    //                     );
    //             }
    //             $ids = trim($ids,',');
    //             $or->where("order_id in(".$ids.")")->save(array('order_status'=>3));
    //             M('order_action')->addAll($data);//订单操作记录
    //         }
    //     }
    // }

    public function changePintRule(){
        $data['pint_can'] = $_POST['pint_can'];
        $data['pint_images'] = trim(implode(',',$_POST['goods_images']),',');
        $data['pint_types'] = implode(',',$_POST['types']);
        $data['pint_rule'] = $_POST['pint_rule'];
        $m = M('config');
        $images = $m->field('value')->where(array('name'=>"pint_images"))->find();
        $images = explode(',',$images['value']);
        $newImages = explode(',',$data['pint_images']);
        foreach($images as $v){
            if(!in_array($v,$newImages)){
                unlink($v);
            }
        }
        $m->where(array('name'=>"pint_can"))->save(array("value"=>$data['pint_can']));
        $m->where(array('name'=>"pint_images"))->save(array("value"=>$data['pint_images']));
        $m->where(array('name'=>"pint_types"))->save(array("value"=>$data['pint_types']));
        $m->where(array('name'=>"pint_rule"))->save(array("value"=>$data['pint_rule']));
        exit(json_encode(array('status' => 1,'msg' => '操作成功')));
    }

    /*
     *订单首页
     */
    public function pintOrder(){
        $begin = date('Y/m/d',(time()-30*60*60*24));//30天前
        $end = date('Y/m/d',strtotime('+1 days'));  
        $this->assign('timegap',$begin.'-'.$end);

        $this->assign('order_status',C('ORDER_STATUS'));
        $this->assign('pay_status',C('PAY_STATUS'));
        $this->assign('shipping_status',C('SHIPPING_STATUS'));
        
        $this->display();
    }

    /*
     *Ajax首页
     */
    public function ajaxPintOrder(){
        $orderLogic = new OrderLogic();

        $timegap = I('timegap');
        if($timegap){
            $gap = explode('-', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        // 搜索条件
        $condition = array();
        $pint_status = I('pint_status',3);
        if($pint_status != 3){
        	$pint_id_arr = M('pint')->where('pint_status = '.$pint_status)->getField('pint_id',true);
	        if($pint_id_arr){
	        	$condition['order_prom_id'] = array('in',$pint_id_arr);
	        }else{
                $this->display();
                die;
            }
        }
        I('consignee') ? $condition['consignee'] = trim(I('consignee')) : false;
        if($begin && $end){
            $condition['add_time'] = array('between',"$begin,$end");
        }
        $store_name = I('store_name','','trim');
        if($store_name)
        {
            $store_id_arr = M('store')->where("store_name like '%$store_name%'")->getField('store_id',true);
            if($store_id_arr)
            {
                $condition['store_id'] = array('in',$store_id_arr);
            }
        }
        $condition['order_prom_type'] = '101';
        I('order_sn') ? $condition['order_sn'] = trim(I('order_sn')) : false;
        I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
        I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
        I('pay_code') != '' ? $condition['pay_code'] = I('pay_code') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
        $sort_order = I('order_by','DESC').' '.I('sort');
        $count = M('order')->where($condition)->where(" !(pay_code!='cod' and pay_status = 0)")->count();
        $Page  = new AjaxPage($count,20);
        //  搜索条件下 分页赋值
      //  foreach($condition as $key=>$val) {
          //  $Page->parameter[$key]   =  urlencode($val);
      //  }
        $show = $Page->show();
        //获取订单列表
        $orderList = $res = M('order')->where($condition)->where(" !(pay_code!='cod' and pay_status = 0) ")->limit($Page->firstRow.','.$Page->listRows)->order($sort_order)->select();
        foreach($orderList as $key=>$value){
            
            $orderList[$key]["pay_name"]=M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>$value['pay_code']))->getField('name'); 
        }
        $store_list = M('store')->getField('store_id,store_name');        
        $this->assign('store_list',$store_list);       
        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出

        $this->assign('order_status',C('ORDER_STATUS'));
        $this->assign('pay_status',C('PAY_STATUS'));
        $this->assign('shipping_status',C('SHIPPING_STATUS'));
        
        $this->display();
    }

    public function export_order()
    {
        //搜索条件
        $where = 'where 1=1 and is_pint=1 ';
        $consignee = I('consignee');
        if($consignee){
            $where .= "AND consignee like '%$consignee%' ";
        }
        $order_sn =  I('order_sn');
        if($order_sn){
            $where .= "AND order_sn = '$order_sn' ";
        }
        if(I('order_status')){
            $where .= "AND order_status = ".I('order_status');
        }
        
        $timegap = I('timegap');
        if($timegap){
            $gap = explode('-', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
            $where .= "AND add_time>$begin and add_time<$end";
        }
    $region = M('region')->getField('id,name');
                
    $sql = "select *,FROM_UNIXTIME(add_time,'%Y-%m-%d') as create_time from __PREFIX__order $where order by order_id";
        $orderList = D()->query($sql);   
        $strTable ='<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">订单编号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">日期</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货人</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货地址</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">电话</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">实际支付</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付方式</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">发货状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">商品信息</td>';
        $strTable .= '</tr>';
        
        foreach($orderList as $k=>$val){
            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_sn'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['create_time'].' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['consignee'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'."{$region[$val['province']]},{$region[$val['city']]},{$region[$val['district']]},{$region[$val['twon']]}{$val['address']}".' </td>';                
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['mobile'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['goods_price'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['order_amount'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['pay_name'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$this->pay_status[$val['pay_status']].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$this->shipping_status[$val['shipping_status']].'</td>';    
            $orderGoods = D('order_goods')->where('order_id='.$val['order_id'])->select();
            $strGoods="";
            foreach($orderGoods as $goods){
                $strGoods .= "商品编号：".$goods['goods_sn']." 商品名称：".$goods['goods_name'];
                if ($goods['spec_key_name'] != '') $strGoods .= " 规格：".$goods['spec_key_name'];
                $strGoods .= "<br />";
            }
            unset($orderGoods);
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$strGoods.' </td>';
            $strTable .= '</tr>';
        }
        $strTable .='</table>';
        unset($orderList);
        downloadExcel($strTable,'order');
        exit();
    }
}